package com.qms.qep.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qms.common.annotation.Log;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.enums.BusinessType;
import com.qms.common.utils.poi.ExcelUtil;
import com.qms.qep.domain.InspectionTask;
import com.qms.qep.domain.dto.InspectionTaskDTO;
import com.qms.qep.service.IInspectionTaskService;
import com.qms.common.core.page.TableDataInfo;

/**
 * 检验任务Controller
 */
@RestController
@RequestMapping("/qep/inspection/task")
public class InspectionTaskController extends BaseController {
    @Autowired
    private IInspectionTaskService inspectionTaskService;

    /**
     * 查询检验任务列表
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(InspectionTask inspectionTask) {
        startPage();
        List<InspectionTask> list = inspectionTaskService.selectInspectionTaskList(inspectionTask);
        return getDataTable(list);
    }
    
    /**
     * 查询检验任务DTO列表
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:list')")
    @GetMapping("/listDTO")
    public TableDataInfo listDTO(InspectionTask inspectionTask) {
        startPage();
        List<InspectionTaskDTO> list = inspectionTaskService.selectInspectionTaskDTOList(inspectionTask);
        return getDataTable(list);
    }

    /**
     * 导出检验任务列表
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:export')")
    @Log(title = "检验任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, InspectionTask inspectionTask) {
        List<InspectionTask> list = inspectionTaskService.selectInspectionTaskList(inspectionTask);
        ExcelUtil<InspectionTask> util = new ExcelUtil<InspectionTask>(InspectionTask.class);
        util.exportExcel(response, list, "检验任务数据");
    }

    /**
     * 获取检验任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(inspectionTaskService.selectInspectionTaskById(id));
    }

    /**
     * 新增检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:add')")
    @Log(title = "检验任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody InspectionTask inspectionTask) {
        return toAjax(inspectionTaskService.insertInspectionTask(inspectionTask));
    }

    /**
     * 修改检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:edit')")
    @Log(title = "检验任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody InspectionTask inspectionTask) {
        return toAjax(inspectionTaskService.updateInspectionTask(inspectionTask));
    }

    /**
     * 删除检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:remove')")
    @Log(title = "检验任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(inspectionTaskService.deleteInspectionTaskByIds(ids));
    }
    
    /**
     * 分配检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:assign')")
    @Log(title = "检验任务", businessType = BusinessType.UPDATE)
    @PutMapping("/assign")
    public AjaxResult assign(@RequestBody InspectionTask inspectionTask) {
        if (inspectionTask == null || inspectionTask.getId() == null) {
            return error("参数错误：任务ID不能为空");
        }
        
        try {
            // 打印接收到的数据
            System.out.println("接收到分配任务请求，详情：");
            System.out.println("任务ID: " + inspectionTask.getId());
            System.out.println("检验人员: " + inspectionTask.getInspector());
            
            // 参数验证
            if (inspectionTask.getInspector() == null || inspectionTask.getInspector().trim().isEmpty()) {
                return error("参数错误：检验人员不能为空");
            }
            
            // 执行分配
            int rows = inspectionTaskService.assignInspectionTask(inspectionTask);
            if (rows > 0) {
                return success("任务分配成功");
            } else {
                return error("任务分配失败，请稍后重试");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error("任务分配异常：" + e.getMessage());
        }
    }
    
    /**
     * 开始检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:start')")
    @Log(title = "检验任务", businessType = BusinessType.UPDATE)
    @PutMapping("/start/{id}")
    public AjaxResult start(@PathVariable("id") Integer id) {
        return toAjax(inspectionTaskService.startInspectionTask(id));
    }
    
    /**
     * 完成检验任务
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:finish')")
    @Log(title = "检验任务", businessType = BusinessType.UPDATE)
    @PutMapping("/finish")
    public AjaxResult finish(@RequestBody InspectionTask inspectionTask) {
        return toAjax(inspectionTaskService.finishInspectionTask(inspectionTask));
    }
    
    /**
     * 获取任务统计数据
     */
    @PreAuthorize("@ss.hasPermi('qep:inspection:task:statistics')")
    @GetMapping("/statistics")
    public AjaxResult statistics() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("waiting", inspectionTaskService.countInspectionTaskByStatus(1));
        ajax.put("processing", inspectionTaskService.countInspectionTaskByStatus(2));
        ajax.put("completed", inspectionTaskService.countInspectionTaskByStatus(3));
        ajax.put("results", inspectionTaskService.selectInspectionTaskStatistics());
        ajax.put("monthly", inspectionTaskService.selectInspectionTaskMonthlyStatistics());
        return ajax;
    }
    
    /**
     * 生成任务编号
     */
    @GetMapping("/generateCode")
    public AjaxResult generateTaskCode() {
        return success(inspectionTaskService.generateTaskCode());
    }
} 